<template>
	<view class="container">
		<!-- 顶部导航栏 -->
<!-- 		<view class="nav-bar">
			<view class="left">
				<u-icon name="arrow-left" size="32" color="#333" @click="goBack"></u-icon>
			</view>
			<view class="title">{{ questionaire.name }}</view>
		</view> -->
		<!-- 内容区域 -->
        <scroll-view class="content-scroll" scroll-y>
          <view class="content">
            <view
              class="question-item"
              v-for="(question, qIndex) in questionaire.questionaireQuestionList"
              :key="question.id"
			  v-show="!(hide34 && (qIndex === 2 || qIndex === 3))"
            >
              <!-- 问题标题 -->
              <view class="question-title">
                {{ qIndex }}. {{ question.content }}
              </view>
        
              <!-- 百分比滑动题 -->
              <view v-if="question.content.includes('百分比')" class="slider-container">
                <view class="slider-scale">
                  <text
                    v-for="value in [0,10,20,30,40,50,60,70,80,90,100]"
                    :key="value"
                  >{{ value }}</text>
                </view>
                <slider
                  :value="sliderValues[question.id] || 0"
                  min="0"
                  max="100"
                  step="10"
                  show-value
                  block-size="24"
                  @change="onSliderChange(question, $event)"
                />
                <view class="slider-labels">
                  <text>%</text>
                </view>
              </view>
        
              <!-- 普通选择题 -->
              <view v-else class="options">
                <view
                  class="option-item"
                  v-for="(item, oIndex) in question.questionaireSelectVoList"
                  :key="item.id"
                  :class="{ 'active': userAnswers[question.id] === item.id }"
                  @click="selectOption(question.id, item.id)"
                >
                  <view
                    class="radio-circle"
                    :class="{ 'checked': userAnswers[question.id] === item.id }"
                  >
                    <view class="inner-circle" v-if="userAnswers[question.id] === item.id"></view>
                  </view>
                  <text>{{ item.content }}</text>
                </view>
              </view>
            </view>
        
            <!-- 提交按钮 -->
            <view class="submit-btn" @click="submitForm">
              <text>提交</text>
            </view>
          </view>
        </scroll-view>

	</view>
</template>

<script> 
import { getQuestionaireAllDetail, submitAnswers } from '@/common/api';

export default {
	data() {
		return {
			questionaireId: '',
			questionaire: [], // 问卷所有信息
			userAnswers: {},  // 存储所有用户答案：{ questionId: selectId }
			sliderValues: {}, // 存储滑动条当前值：{ questionId: value }
			hide34: false, // 是否隐藏第3和第4题
		}
	},
	onLoad(options) {
		this.questionaireId = options.id;
		this.loadData();
	},
	methods: {
		// 获取问卷数据
		async loadData() {
			try {
				const qRes = await getQuestionaireAllDetail(this.questionaireId);
				this.questionaire = qRes.data;
				console.log(this.questionaire);
			} catch (e) {
				console.error('加载问卷失败', e);
			}
		},

		// 普通选择题选择
		selectOption(questionId, optionId) {
			this.userAnswers[questionId] = optionId;
			// 判断是否为第2题
		  const allQuestions = this.questionaire.questionaireQuestionList;
		  const secondQuestion = allQuestions?.[1];
		
		  if (questionId === secondQuestion?.id) {
			// 如果选择第一个或第二个选项（可根据实际 id 判断）
			if (optionId === secondQuestion.questionaireSelectVoList[0]?.id || optionId === secondQuestion.questionaireSelectVoList[1]?.id) {
			  this.hide34 = true;
			  // 清空第3、4题答案
			  const thirdId = allQuestions?.[2]?.id;
			  const fourthId = allQuestions?.[3]?.id;
			  if (thirdId) this.userAnswers[thirdId] = null;
			  if (fourthId) this.userAnswers[fourthId] = null;
			} else {
			  this.hide34 = false;
			}
		  }
		},

		// 滑动条变化
		onSliderChange(question, e) {
			const value = e.detail.value;
			const questionId = question.id;
			this.sliderValues[questionId] = value;

			const matched = question.questionaireSelectVoList.find(
				(opt) => opt.content == `${value}` || opt.content == `${value}%`
			);
			if (matched) {
				this.userAnswers[questionId] = matched.id;
			} else {
				console.warn(`滑动值 ${value} 未匹配到选项`);
			}
		},

		// 提交处理
		async submitForm() {
			const allQuestions = this.questionaire.questionaireQuestionList || [];

			// 1. 校验是否每题都有答案
			const unanswered = allQuestions.filter(q => {
			    const isHidden = this.hide34 && (q === allQuestions[2] || q === allQuestions[3]);
			    return !isHidden && !(q.id in this.userAnswers);
			  });
			if (unanswered.length > 0) {
				uni.showToast({
					title: '请完成所有题目再提交',
					icon: 'none'
				});
				return;
			}

			// 2. 构造提交数据
			  const data = allQuestions.map(q => {
				const isHidden = this.hide34 && (q === allQuestions[2] || q === allQuestions[3]);
				const selectId = isHidden ? null : this.userAnswers[q.id] ?? null;
				return {
				  questionId: q.id,
				  selectId
				};
			  });
	
			// 3. 发起提交请求
			try {
				const res = await submitAnswers(data);
				uni.showToast({
					title: '提交成功',
					icon: 'success'
				});
				// 提交成功后延时返回上一个页面
				setTimeout(() => {
						uni.navigateBack();
					}, 1500);
			} catch (error) {
				uni.showToast({
					title: error.message || '网络错误',
					icon: 'none'
				});
			}
		},

		// 返回上一页
		goBack() {
			uni.navigateBack();
		}
	}
}
</script>


<style lang="scss">
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		
		.nav-bar {
			background-color: #fff;
			padding: 20rpx 30rpx;
			display: flex;
			align-items: center;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
			
			.title {
				flex: 1;
				text-align: center;
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-right: 32rpx;
			}
			
			.left {
				width: 60rpx;
			}
		}
		
		.content-scroll {
			flex: 1;
			height: calc(100vh - 100rpx);
		}
		
		.content {
			padding: 20rpx 30rpx;
			
			.question-item {
				background-color: #fff;
				border-radius: 12rpx;
				padding: 30rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
				
				.question-title {
					font-size: 32rpx;
					color: #333;
					margin-bottom: 30rpx;
					line-height: 1.5;
				}
				
				.options {
					.option-item {
						display: flex;
						align-items: center;
						padding: 20rpx 0;
						margin-bottom: 10rpx;
						
						.radio-circle {
							width: 36rpx;
							height: 36rpx;
							border-radius: 50%;
							border: 2rpx solid #ccc;
							margin-right: 20rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							
							&.checked {
								border-color: #1890FF;
							}
							
							.inner-circle {
								width: 20rpx;
								height: 20rpx;
								border-radius: 50%;
								background-color: #1890FF;
							}
						}
						
						text {
							font-size: 28rpx;
							color: #333;
						}
						
						&.active {
							text {
								color: #1890FF;
							}
						}
					}
				}
				
				.slider-container {
					padding: 20rpx 0;
					
					.slider-scale {
						display: flex;
						justify-content: space-between;
						margin-bottom: 10rpx;
						padding: 0 4rpx;
						
						text {
							font-size: 26rpx;
							color: #666;
							transform: translateX(-50%);
							
							&:first-child {
								transform: translateX(0);
							}
							
							&:last-child {
								transform: translateX(-100%);
							}
						}
					}
					
					.slider-labels {
						display: flex;
						justify-content: flex-end;
						margin-top: 10rpx;
						
						text {
							font-size: 26rpx;
							color: #666;
						}
					}
				}
			}
			
			.submit-btn {
				background-color: #1890FF;
				height: 90rpx;
				border-radius: 45rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 40rpx 0;
				
				text {
					color: #fff;
					font-size: 32rpx;
					font-weight: bold;
				}
			}
		}
	}
</style> 